package util

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log"
	"math"
	"strconv"
	"strings"
)

//
func IntToBytes(n int, islittle bool) []byte {
	x := int32(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	if islittle {
		binary.Write(bytesBuffer, binary.LittleEndian, x)
	} else {
		binary.Write(bytesBuffer, binary.BigEndian, x)
	}

	return bytesBuffer.Bytes()
}
func Int8ToByte(n int8, islittle bool) byte {
	x := int8(n)

	bytesBuffer := bytes.NewBuffer([]byte{})
	if islittle {
		binary.Write(bytesBuffer, binary.LittleEndian, x)
	} else {
		binary.Write(bytesBuffer, binary.BigEndian, x)
	}
	tmp := bytesBuffer.Bytes()
	_ = bytesBuffer
	return tmp[0]
}
func Int16ToByte(n int16, islittle bool) []byte {
	x := int16(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	if islittle {
		binary.Write(bytesBuffer, binary.LittleEndian, x)
	} else {
		binary.Write(bytesBuffer, binary.BigEndian, x)
	}
	return bytesBuffer.Bytes()
}

//
func BytesToInt(b []byte, islittle bool) int {
	bytesBuffer := bytes.NewBuffer(b)
	var x int32
	if islittle {
		binary.Read(bytesBuffer, binary.LittleEndian, &x)
	} else {
		binary.Read(bytesBuffer, binary.BigEndian, &x)
	}
	_ = bytesBuffer
	return int(x)
}
func BytesToInt16(b []byte, islittle bool) int16 {
	bytesBuffer := bytes.NewBuffer(b)
	var x int16
	if islittle {
		binary.Read(bytesBuffer, binary.LittleEndian, &x)
	} else {
		binary.Read(bytesBuffer, binary.BigEndian, &x)
	}
	_ = bytesBuffer
	return int16(x)
}
func BytesToFloat32(buf []byte, islittle bool) float32 {
	var v uint32
	if islittle {
		v = binary.LittleEndian.Uint32(buf)
	} else {
		v = binary.BigEndian.Uint32(buf)
	}
	f := math.Float32frombits(v)
	return f
}
func Printpacket(message string) {
	log.Println("msg len is", strings.Count(message, "")-1)
	reqLen := strings.Count(message, "") - 1
	buffer := new(bytes.Buffer)
	data := []byte(message)
	defer func() {
		_ = buffer
		_ = data
	}()
	for _, b := range data[:reqLen] {

		s := strconv.FormatInt(int64(b&0xFF), 16)
		if len(s) == 1 {
			buffer.WriteString("0")
		}
		s += " "
		buffer.WriteString(s)
	}
	fmt.Println(buffer.String())
}
